package usf.vend.a.bull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import android.os.Bundle;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import android.location.*;
 
public class GMapActivity extends MapActivity implements LocationListener 
{	
	//private TextView locationTypeTextView;
    //private TextView locationDataTextView;
    private LocationManager theLocMan;
    
    private MyMapView mapView;
    private LocationOverlay theMapOverlay;

    private boolean isAdded = false;
    
    private Location currentLocation;
    
    Bundle bundle = new Bundle();
    
    List<Overlay> mapOverlays;
    Drawable machinePin;
    MapItemizedOverlay machineOverlay;
    
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);       
        
        //locationTypeTextView = (TextView) findViewById(R.id.textView4);
        //locationDataTextView = (TextView) findViewById(R.id.textView1);
        getInitialLocation();
        initializeMap();
        
        mapOverlays = mapView.getOverlays();
        machinePin = this.getResources().getDrawable(R.drawable.pin_small);
        machineOverlay = new MapItemizedOverlay(machinePin, this); 
    }
    
    @Override
    public void onStop(){
    	super.onStop();
    	theLocMan.removeUpdates(this);
    }
    
    @Override
    public void onRestart(){
    	theLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	theLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    	theLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }
    
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    //location
    @Override
    public void onLocationChanged(Location loc){
    	/*
    	String locProv = loc.getProvider();
    	
    	if(locProv.equals(LocationManager.GPS_PROVIDER)){
    		locationTypeTextView.setText("GPS Provider");
    	}
    	else{
    		locationTypeTextView.setText("Network Provider");
    	}
    	locationDataTextView.setText(loc.getLatitude()+","+loc.getLongitude());
    	*/
    	currentLocation = loc;
    	updateOverlayLocation(loc);
    }
    
    @Override
    public void onProviderDisabled(String arg0){
    }
    
    @Override
    public void onProviderEnabled(String arg0) {
    }
    
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    	}
    
    private void updateOverlayLocation(Location arg0) {
    	MapController mapController = mapView.getController();
    	Context con = getBaseContext();
    	GeoPoint p = new GeoPoint ((int) (arg0.getLatitude() * 1E6), (int) (arg0.getLongitude() * 1E6));
    	
    	theMapOverlay.setPoint(p, con);
    	
    	if(!isAdded)
    	{
    		//mapView.getOverlays().clear();
    		mapView.getOverlays().add(theMapOverlay);
    		
    		mapController.animateTo(p);
    		mapController.setZoom(17);
    		mapController.setCenter(p);
    		isAdded = true;
    	}
    	mapView.postInvalidate();
    	
    }
    
    private void centerMap(GeoPoint point)
    {
    	MapController mapController = mapView.getController();
    	//Context con = getBaseContext();
    	
    	//theMapOverlay.setPoint(p, con);
    	

		//mapView.getOverlays().clear();
		//mapView.getOverlays().add(theMapOverlay);
		
		mapController.animateTo(point);
		mapController.setZoom(16);
		//isAdded = true;

    	mapController.setCenter(point);
    	mapView.postInvalidate();
    	
    }
    
    private void initializeMap()
    {
    	mapView = (MyMapView)findViewById(R.id.mapview);
    	mapView.setBuiltInZoomControls(true);
    	mapView.setStreetView(true);
    	mapView.setSatellite(false);
    	theMapOverlay = new LocationOverlay(this);
    }
    private void getInitialLocation(){
    	theLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	theLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    	theLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    	//Location lastKnown = theLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    	//if(lastKnown != null){
    		//locationDataTextView.setText(lastKnown.getLatitude()+","+lastKnown.getLongitude());
    		//locationTypeTextView.setText("GPS Cached Location");
    		//updateOverlayLocation(lastKnown);
    	//}
    	//else if ((lastKnown = theLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) != null){
    		//locationDataTextView.setText(lastKnown.getLatitude()+","+lastKnown.getLongitude());
    		//locationTypeTextView.setText("Network Cached Location");
    		//updateOverlayLocation(lastKnown);
    	//}
    	//else{
    		//locationTypeTextView.setText("Determining Location...");
    	//}
    }
    
    private void onSearchReturn()
    {
    	double lat = (double) 0;
    	double lng = (double) 0;
    	ArrayList<String> coordinates = bundle.getStringArrayList("coordinates");
    	if (coordinates.isEmpty())
    	{
    		Toast toast = Toast.makeText(getApplicationContext(), "No results matched your search.", Toast.LENGTH_SHORT);
    		toast.show();
    		return;
    	}
    	Iterator<String> coorIterator = coordinates.iterator();
    	machineOverlay.clear();
    	while (coorIterator.hasNext())
    	{
    		String coors = coorIterator.next();
    		String[] splitCoors = coors.split("[,]");
    		Log.d("GMapActivity", splitCoors[0] + " and " + splitCoors[1]);
    		lat = Float.valueOf(splitCoors[0]);
    		lng = Float.valueOf(splitCoors[1]);
    		machineOverlay.addOverlay(new OverlayItem(new GeoPoint ((int) (lat * 1E6), (int) (lng * 1E6)), "location", ""));
    	}
    	mapOverlays.add(machineOverlay);
    	GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
    	centerMap(point);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	if (resultCode == RESULT_CANCELED)
    		return;
    	bundle = data.getExtras();
    	onSearchReturn();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	menu.clear();
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.mapmenu, menu);
	    return true;
	}
    	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		bundle.putString("location", currentLocation.getLatitude() +","+ currentLocation.getLongitude());
	    switch (item.getItemId()) {
		    case R.id.search:
		    	startActivityForResult(new Intent(this, SearchActivity.class).putExtras(bundle), 0);
	            break;
	        case R.id.switch_view:
	        	if (mapView.isSatellite())
	        	{
	        		mapView.setStreetView(true);
	        		mapView.setSatellite(false);
	        		mapView.invalidate();
	        	}
	        	else
	        	{
	        		mapView.setSatellite(true);
	        		mapView.setStreetView(false);
	        		mapView.invalidate();
	        	}
	    }
	    return true;
	}
}